﻿using System;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Management.Smo;
using Settings = NazTek.Utility.Properties.Settings;

namespace NazTek.Utility.Extensions.SqlObject
{
    /// <summary>
    /// Extends SMO Table's column collection object type.
    /// </summary>
    public static class ColumnCollectionExtension
    {
        /// <summary>
        /// Gets a comma separated list of column names.
        /// </summary>
        /// <param name="columnCollection">The collection to inspect for names.</param>
        /// <param name="prefix">When not null, prefixes the column names followed by period.</param>
        /// <param name="exclusions">List of names to exclude from final list.</param>
        /// <returns>List of column names except for the ones in the exclusions list, if any.</returns>
        public static string GetNames(this ColumnCollection columnCollection, string prefix, params string[] exclusions)
        {
            var names = new StringBuilder();
            for (var i = 0; i < columnCollection.Count; i++)
            {
                if (exclusions == null || exclusions.Length == 0 || !exclusions.ToList().Contains(columnCollection[i].Name))
                    names.AppendFormat("{0}[{1}]{2}", string.IsNullOrWhiteSpace(prefix) ? "" : string.Format("{0}.", prefix),
                        columnCollection[i].Name, Settings.Default.Separator);
            }
            return names.ToString().TrimEnd(Settings.Default.Separator.ToCharArray());
        }

        /// <summary>
        /// Removes columns from a target list, if any are missing in a source list.
        /// </summary>
        /// <param name="srcColumns">The list provides the basis for comparison.</param>
        /// <param name="targetColumns">The list to remove column(s) from, when missing in source.</param>
        /// <param name="targetIndex">Position of the column in the target list to inspect for existence in source.</param>
        /// <param name="publishNotice">Notifies client when a column is removed from target list.</param>
        /// <returns>True when target list is modified, otherwise false.</returns>
        public static bool Sync(this ColumnCollection srcColumns, ColumnCollection targetColumns, int targetIndex,
            Action<string> publishNotice)
        {
            var targetColumn = targetColumns[targetIndex].Name;
            if (srcColumns.Contains(targetColumn))
                return false;
            publishNotice(string.Format("Removing column: {0}", targetColumn));
            targetColumns[targetColumn].Drop();
            return true;
        }
    }
}
